<template>
  <div class="order flex">
    <!-- 侧边栏组件 -->
    <Aside></Aside>
    <div :class="store.state ? 'bodyw1' : 'bodyw'">
      <!-- 导航栏组件 -->
      <Nav
        @searchOrderList="searchOrderList"
        @getOrderList="getOrderList"
      ></Nav>
      <div class="bodybox flex">
        <!-- 销售单左边 -->
        <div
          v-if="radio1 === '1'"
          :class="state ? 'left ml-10 leftwidth1' : 'left ml-10 leftwidth2'"
        >
          <!-- 销售单列表组件 -->
          <SalesOrderlist
            ref="salesOrderlist"
            :customerList="customerList"
            :sorderLeading="sorderLeading"
            :order_id="order_id * 1"
            :orderList="orderList"
            @getSaleCustomer="getSaleCustomer"
            @getOrderList="getOrderList"
            @SelectionMethod="SelectionMethod"
            @change="change"
            @getorder="getorder"
            @refreshOrderList="refreshOrderList"
          />
          <!-- 销售单曲线图组件 -->
          <SalesChart ref="purchaseChart1" />
        </div>
        <!--采购单左边 -->
        <div
          v-if="radio1 === '2'"
          :class="state ? 'left ml-10 leftwidth1' : 'left ml-10 leftwidth2'"
        >
          <PurchaseTakelist
            ref="takeList"
            :takeLeading="takeLeading"
            :purchaseordertesk_id="purchaseordertesk_id * 1"
            @SelectionMethod="SelectionMethod"
            :purcharseTakeList="purcharseTakeList"
            @change="change"
            @getPurTake="getPurTake"
            @refreshPurTakeList="refreshPurTakeList"
          />
          <PurchaseOrderlist
            @getPurOrderID="getPurOrderID"
            @getPurchaseOrderList1="getPurchaseOrderList1"
            :poLeading="poLeading"
            :purchaseorder_id="purchaseorder_id * 1"
            :purchaseOrderDetailList="purchaseOrderDetailList"
          />
        </div>
        <!-- center -->
        <div :class="state ? 'center centerwidth1' : 'center centerwidth2'">
          <div class="flex aic title">
            <!-- 公共 -->
            <el-radio-group v-model="radio1" @change="switchover" class="ml-4">
              <!-- 销售单 -->
              <el-radio
                label="1"
                size="large"
                :disabled="store.type == 3 ? true : false"
              >
                Sales Order
              </el-radio>
              <!-- 采购单 -->
              <el-radio
                label="2"
                size="large"
                :disabled="store.type == 2 || store.type == 4 ? true : false"
              >
                Purchase Order
              </el-radio>
            </el-radio-group>
            <Title
              :radio1="radio1"
              :CreateTime="CreateTime"
              :orderTitle="orderTitle"
              :purTitle="purTitle"
              :purTime="purTime"
            ></Title>
          </div>
          <!-- 销售单中间头部地址选择开始 -->
          <div v-if="radio1 === '1'" class="choose flex jc-sb">
            <Chooseinfo
              @userinfo="userinfo"
              @getUser1="getUser1"
              @getUser="getUser"
              @supInfo="supInfo"
              @getSuppier="getSuppier"
              @paymentinfo="paymentinfo"
              @getPayment="getPayment"
              @getCurrent="getCurrent"
              :currentList="currentList"
              :payinfo="payinfo"
              :paymentList="paymentList"
              :suppierInfo="suppierInfo"
              :supplierList="supplierList"
              :userAddress="userAddress"
              :userList="userList"
              :sorderState="sorderState"
              :sInfo="sInfo"
            />
          </div>
          <!-- 销售单详情 -->
          <div v-if="radio1 === '1'" class="sorderbody">
            <Sbutton
              @open="open"
              @orderDelete="orderDelete"
              :isclose="isclose"
              :checked="checked"
            />
            <!-- 销售单产品列表和新建订单列表开始 -->
            <SalesProductlist
              v-if="!state1"
              @getleading="getleading"
              @getCondition="getCondition"
              @insertId="insertId"
              @cancelEvent="cancelEvent"
              @changePrice="changePrice"
              @deleteProduct="deleteProduct"
              @getProductID="getProductID"
              @getBrand="getBrand"
              @getModel="getModel"
              :sDetailLeading="sDetailLeading"
              :checked="checked"
              :checked1="checked1"
              :checked2="checked2"
              :conditionList="conditionList"
              :leadingList="leadingList"
              :brandList="brandList"
              :modelList="modelList"
              :orderDetails="orderDetails"
              :sorderState="sorderState"
              :state="state"
            />
            <SalesNeworder
              v-else
              @newDeleteProduct="newDeleteProduct"
              @getqtnid="getqtnid"
              @getBrand="getBrand"
              @getModel="getModel"
              @chooseDescr="chooseDescr"
              :neworderList="neworderList"
              :conditionList="conditionList"
              :leadingList="leadingList"
              :brandList="brandList"
              :modelList="modelList"
              :orderDetails="orderDetails"
              :state="state"
            />
            <!-- 销售中间底部开始 -->
            <Sfootermoney
              @open1="open1"
              :sInfo="sInfo"
              :discountInfo="discountInfo"
              :vatInfo="vatInfo"
              :totalInfo="totalInfo"
              :paymentFeeInfo="paymentFeeInfo"
              :shippingCostInfo="shippingCostInfo"
              :subTotal="subTotal * 1"
              :paymentRecieved="paymentRecieved"
            >
            </Sfootermoney>
          </div>
          <!-- 采购开始 -->
          <div v-if="radio1 === '2'" class="porderbody">
            <!-- 按钮组件 -->
            <Pbutton
              @openNewOrder="openNewOrder"
              @allocationMethod="allocationMethod"
              @taskDelete="taskDelete"
              :allocationState="allocationState"
            />
            <!-- 采购任务详情组件 -->
            <div v-if="radio1 === '2'">
              <PurchaseTakedetail
                @getBuyerList="getBuyerList"
                @cancelEvent="cancelEvent"
                @compare="compare"
                @returnTask="returnTask"
                :buyerList="buyerList"
                :takeDetailList="takeDetailList"
                :allocationState="allocationState"
                :state="state"
                :takeDetailLeading="takeDetailLeading"
              />
            </div>
            <!-- 采购列表详情 -->
            <Pdbutton
              @ChangeThePrice="ChangeThePrice"
              @ExportPorder="ExportPorder"
              @deletePurchaseOrder="deletePurchaseOrder"
              :priceState="priceState"
            />
            <div v-if="radio1 === '2'">
              <PurchaseOrderdetail
                @cancelEvent="cancelEvent"
                @choosePrice="choosePrice"
                @delPurchaseDetails="delPurchaseDetails"
                :priceState="priceState"
                :poDetailLeading="poDetailLeading"
                :purOrderDetailList="purOrderDetailList"
                :state="state"
              />
            </div>
          </div>
        </div>
        <!-- 公共右边聊天窗开始 -->
        <div class="right ml-10 mr-10" v-if="state">
          <Right :state="state" />
        </div>
      </div>
    </div>
    <!-- 销售单头部弹窗 -->
    <Clearance
      ref="clearance"
      @ClearanceSave="ClearanceSave"
      @getnumber="getnumber"
      :isrelease="isrelease"
      :declareAmount="declareAmount"
      :totalAmount="totalAmount"
      :sInfo="sInfo"
      :clearList="clearList"
    />
    <Copy
      ref="copy"
      @closeInfo="closeInfo"
      @deleteSolo="deleteSolo"
      @newOrder="newOrder"
      @copyOrderSave="copyOrderSave"
      @copyOrder="copyOrder"
      @SelectionMethod="SelectionMethod"
      @getorderProductList="getorderProductList"
      @getOrderid="getOrderid"
      :order_id="order_id * 1"
      :orderTitle="orderTitle"
      :rightOrder="rightOrder"
      :leftOrder="leftOrder"
      :orderidList="orderidList"
    />
    <FromQtn
      ref="fromqtn"
      @closeInfo="closeInfo"
      @clearQtn="clearQtn"
      @getqtnProductList1="getqtnProductList1"
      @deleteSolo="deleteSolo"
      @qtnnewOrder="qtnnewOrder"
      @qtnSave="qtnSave"
      @qtnAdd="qtnAdd"
      @SelectionMethod="SelectionMethod"
      @getqtnProductList="getqtnProductList"
      :qtnnewList="qtnnewList"
      :qtnProductList="qtnProductList"
      :orderidList="orderidList"
      :order_id="order_id * 1"
      :orderTitle="orderTitle"
      @getOrderid="getOrderid"
    />
    <FromRfq
      ref="fromrfq"
      @closeInfo="closeInfo"
      @clearRfq="clearRfq"
      @getrfqProductList1="getrfqProductList1"
      @deleteSolo="deleteSolo"
      @rfqnewOrder="rfqnewOrder"
      @rfqSave="rfqSave"
      @rfqAdd="rfqAdd"
      @SelectionMethod="SelectionMethod"
      @getrfqProductList="getrfqProductList"
      @getOrderid="getOrderid"
      :rfqnewList="rfqnewList"
      :rfqProductList="rfqProductList"
      :orderidList="orderidList"
      :order_id="order_id * 1"
      :orderTitle="orderTitle"
    />
    <Export
      ref="exportPI"
      @getExcelId="getExcelId"
      :token="store.token"
      :order_id="order_id"
      :excelids="excelids"
      :imgList="imgList"
      :exportPImodels="exportPImodels"
      :capitalTotal="capitalTotal"
      :invoiceInfo="invoiceInfo"
    />
    <PlaceAnOrder
      ref="placeanOrder"
      @getBuyerList="getBuyerList"
      @changeInput1="changeInput1"
      @selectAll="selectAll"
      @changeRadio="changeRadio"
      @purchaseOrderteskAdd="purchaseOrderteskAdd"
      @changePur="changePur"
      :qtySum="qtySum"
      :hqtySum="hqtySum"
      :orderName="orderName"
      :PlaceList="PlaceList"
      :buyerList="buyerList"
      :purList="purList"
    />
    <Delivergoods
      ref="deliverGoods"
      @goodSelectAll="goodSelectAll"
      @changeInput="changeInput"
      @goodsAdd="goodsAdd"
      @changeRadio1="changeRadio1"
      :orderInfoList="orderInfoList"
      :orderName="orderName"
    />
    <!-- 销售单底部弹窗 -->
    <Discount
      ref="discount"
      @discountSave="discountSave"
      @calculation="calculation"
      :sInfo="sInfo"
      :subTotal="subTotal * 1"
    />
    <Vat
      ref="vat"
      @vatSave="vatSave"
      @vatcalculation="vatcalculation"
      :sInfo="sInfo"
      :subTotal="subTotal * 1"
    />
    <ShippingCost
      ref="shippingCost"
      @shippingCostSave="shippingCostSave"
      :sInfo="sInfo"
      :subTotal="subTotal * 1"
    />
    <PaymentFee
      ref="paymentfee"
      @paymentFeecompute="paymentFeecompute"
      @paymentFeeSave="paymentFeeSave"
      :sInfo="sInfo"
      :subTotal="subTotal * 1"
    />
    <!-- 采购弹窗 -->
    <NewPurchaseOrder
      ref="newPurchaseOrder"
      @getPsupplierList="getPsupplierList"
      @changKufang="changKufang"
      @changeNonStock1="changeNonStock1"
      @delecteTacke="delecteTacke"
      @changeNonStock="changeNonStock"
      @CreatePurchaseOrder="CreatePurchaseOrder"
      @inPmoney="inPmoney"
      @inputPqty="inputPqty"
      :pSupplierList="pSupplierList"
      :leadingList="leadingList"
      :createList="createList"
    />
    <ExportPurOrder
      ref="exportPurOrder"
      @closeInfo="closeInfo"
      @closeEpurWindow="closeEpurWindow"
      @getdate="getdate"
      :shortcuts="shortcuts"
      :sumProfit="sumProfit"
      :exportPurList="exportPurList"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 采购订单组件
import Title from "./components/Title.vue";
import Sbutton from "./components/Sbutton.vue";
import Sfootermoney from "./components/Sfootermoney.vue";
import Chooseinfo from "./components/Chooseinfo.vue";
import PurchaseTakelist from "./components/PurchaseTakelist.vue";
import PurchaseTakedetail from "./components/PurchaseTakedetail.vue";
import PurchaseOrderlist from "./components/PurchaseOrderlist.vue";
import PurchaseOrderdetail from "./components/PurchaseOrderdetail.vue";
import Pbutton from "./components/Pbutton.vue";
import Pdbutton from "./components/Pdbutton.vue";
// 采购弹框组件
import NewPurchaseOrder from "./components/PurchaseTopComponents/NewPurchaseOrder.vue";
import ExportPurOrder from "./components/PurchaseTopComponents/ExportPurOrder.vue";
// 销售底部弹框
import ShippingCost from "./components/FooterComponents/ShippingCost.vue";
import PaymentFee from "./components/FooterComponents/PaymentFee.vue";
import Discount from "./components/FooterComponents/Discount.vue";
import Vat from "./components/FooterComponents/Vat.vue";
// 销售订单相关弹框
import Clearance from "./components/TopComponents/Clearance.vue";
import Copy from "./components/TopComponents/Copy.vue";
import FromQtn from "./components/TopComponents/FromQtn.vue";
import FromRfq from "./components/TopComponents/FromRfq.vue";
import Export from "./components/TopComponents/Export.vue";
import PlaceAnOrder from "./components/TopComponents/PlaceAnOrder.vue";
import Delivergoods from "./components/TopComponents/Delivergoods.vue";
// 销售其他组件
import Aside from "../components/Aside.vue";
import Nav from "../components/Nav.vue";
import SalesOrderlist from "./components/SalesOrderlist.vue";
import SalesChart from "./components/SalesChart.vue";
import SalesProductlist from "./components/SalesProductlist.vue";
import SalesNeworder from "./components/SalesNeworder.vue";
// 右侧公共聊天组件
import Right from "./components/Right.vue";
// 相关js方法
import * as api from "../../api1/index";
import * as utils from "./utils.js";
// pinia
import { useDemoStore } from "../../pinia/index";

const store = useDemoStore();
// 顶部单选框
const radio1 = ref("");
// 确认权限
const confirmPermission = () => {
  // 销售和客户
  if (store.type == 2 || store.type == 4) {
    radio1.value = "1";
    // 采购
  } else if (store.type == 3 || store.type === 0) {
    radio1.value = "2";
  } else {
    radio1.value = "1";
  }
};
// 切换
const switchover = (val) => {
  if (val == 2) {
    getpurTakeList();
    getPurchaseOrderList();
  } else {
    getOrderList();
    getleading();
    getCondition();
  }
};
/********************************销售单逻辑开始******************************************** */
// cost shopping复选框
const checked1 = ref(false);
const checked = ref({
  checked1: false,
  checked2: false,
});
const checked2 = ref(false);
const token = store.token;

const sInfo = ref({
  userValue: "",
  suppierValue: "",
  orderType: 0,
  paymentvalue: "",
  currencyType: "",
});
/**获取供应商开始 */
const suppliers = ref([]);
const supplierList = ref([]);
const getSuppier = () => {
  api.orderSupplier({ token: token }).then((res) => {
    suppliers.value = res.data;
    supplierList.value = res.data.map((item) => {
      let label = item.config_short;
      let value = item.config_short;
      return {
        label,
        value,
      };
    });
  });
};
// 选择供应商后触发
const suppierInfo = ref("");
const company_id = ref("");
const supInfo = (val) => {
  suppierInfo.value = suppliers.value.filter(
    (item) => item.config_short === val
  )[0].config_value;
  company_id.value = suppliers.value.filter(
    (item) => item.config_short === val
  )[0].config_id;
};
/**获取供应商结束 */

/**获取银行列表开始 */
const paymentList = ref([]);
const payments = ref([]);
const bankType = ref("");
const bankID = ref("");
// 订单默认银行id
const getPayment = () => {
  const data3 = {
    token: token,
    country_id: 2,
  };
  api.orderPayment(data3).then((res) => {
    payments.value = res.data;
    paymentList.value =
      res.data &&
      res.data.map((item) => {
        let label = item.bank_name;
        let value = item.bank_id;
        return {
          label,
          value,
        };
      });
  });
};
// 选择银行后触发
const payinfo = ref("");
const paymentinfo = (val) => {
  bankID.value = val;
  payinfo.value =
    payments.value.filter((item) => item.bank_id === val)[0] &&
    payments.value.filter((item) => item.bank_id === val)[0].bank_info;
  bankType.value =
    payments.value.filter((item) => item.bank_id === val)[0] &&
    payments.value.filter((item) => item.bank_id === val)[0].bank_type;
};
/**获取银行列表结束 */

/** 获取用户列表开始*/
const users = ref([]);
const userList = ref([]);
// 客户选择后展示的内容
const userdata = {
  token: token,
  kw: "",
  is_supplier: "",
  page: 0,
};
const getUser = (val) => {
  userdata.is_supplier = 0;
  userdata.kw = val;
  userdata.page = 1;
  utils.debounce(500, () => {
    api.orderUser(userdata).then((res) => {
      users.value = res.data.data;
      userList.value =
        res.data.data &&
        res.data.data.map((item) => {
          let label = item.firstname;
          let value = item.customer_info_id;
          return {
            value,
            label,
          };
        });
    });
  });
};
const userlistlength = ref(1);
const getUser1 = () => {
  if (!userlistlength.value) {
    return false;
  }
  userdata.page++;
  api.orderUser(userdata).then((res) => {
    userlistlength.value = res.data.data.length;
    users.value = [...users.value, ...res.data.data];
    userList.value = [
      ...userList.value,
      ...(res.data.data &&
        res.data.data.map((item) => {
          let label = item.firstname;
          let value = item.customer_info_id;
          return {
            value,
            label,
          };
        })),
    ];
  });
};
// 客户地址
const userAddress = ref("");
// 客户名
const firstName = ref("");
const lastName = ref("");
const usersID = ref("");
// 选择用户后触发
const userinfo = (val) => {
  userAddress.value =
    users.value.filter((item) => item.customer_info_id === val)[0] &&
    users.value.filter((item) => item.customer_info_id === val)[0].address +
      "客户公司地址";
  firstName.value =
    users.value.filter((item) => item.customer_info_id === val)[0] &&
    users.value.filter((item) => item.customer_info_id === val)[0].firstname;
  lastName.value =
    users.value.filter((item) => item.customer_info_id === val)[0] &&
    users.value.filter((item) => item.customer_info_id === val)[0].lastname;
  usersID.value =
    users.value.filter((item) => item.customer_info_id === val)[0] &&
    users.value.filter((item) => item.customer_info_id === val)[0]
      .customer_info_id;
};
/** 获取用户列表结束*/

/** 获取货币类型开始 */
const currentList = ref([]);
const getCurrent = () => {
  api.ordersConfigCurrent({ token: token }).then((res) => {
    currentList.value = res.data && res.data;
  });
};
/** 获取货币类型结束 */

/**获取订单开始 */
const salesOrderlist = ref();
const sorderLeading = ref(true);
const orderList = ref([]);
let data = {
  token: token,
  user_uid: "",
  page: "",
  PI_name: "",
  rows: 10,
  is_team: 0,
};
// 订单状态
const sorderState = ref(1);
const getOrderList = (val) => {
  data.user_uid = val;
  data.page = 1;
  sorderRequest();
};
// 上拉加载
const sorderlength = ref(1);
const refreshOrderList = () => {
  if (orderList.value.length == 0 || sorderlength.value == 0) return false;
  data.page++;
  api.orderList(data).then((res) => {
    sorderlength.value = res.data.data && res.data.data.length;
    orderList.value = [
      ...orderList.value,
      ...(res.data.data &&
        res.data.data.map((item) => {
          item.firstname = item.firstname && item.firstname.slice(0, 7);
          return item;
        })),
    ];
    setTimeout(() => {
      sorderState.value = orderList.value[0] && orderList.value[0].State;
      salesOrderlist.value.refsOrderList.toggleRowSelection(
        orderList.value.filter((item) => item.order_id == order_id.value)[0],
        true
      );
    });
  });
};
const sorderRequest = () => {
  data.page = 1;
  api.orderList(data).then((res) => {
    sorderLeading.value = false;
    orderList.value =
      res.data.data &&
      res.data.data.map((item) => {
        item.firstname = item.firstname && item.firstname.slice(0, 7);
        return item;
      });
    setTimeout(() => {
      sorderState.value = orderList.value && orderList.value[0].State;
      salesOrderlist.value.refsOrderList.toggleRowSelection(
        orderList.value ? orderList.value[0] : [],
        true
      );
    });
    //默认以第一个订单渲染详情
    getorder1();
  });
};
const customerData = {
  token: token,
  page: 1,
  pageSize: 30,
  firstname: "",
};
// 获取销售的客户
const customerList = ref([]);
const getSaleCustomer = (val) => {
  if (!val) {
    api.ordersConfigGetMissuUser(customerData).then((res) => {
      customerList.value =
        res.data.data &&
        res.data.data.map((item) => {
          item.firstname = item.firstname + item.lastname;
          item.firstname = item.firstname.slice(0, 40);
          return item;
        });
    });
  } else {
    customerData.firstname = val;
    utils.debounce(500, () => {
      api.ordersConfigGetMissuUser(customerData).then((res) => {
        customerList.value =
          res.data.data &&
          res.data.data.map((item) => {
            item.firstname = item.firstname + item.lastname;
            item.firstname = item.firstname.slice(0, 40);
            return item;
          });
      });
    });
  }
};

// 获取订单详情
const orderTitle = ref("");
const CreateTime = ref("");
const orderDetails = ref([]);
const product_id = ref([]);
const sDetailLeading = ref(false);
// 订单id
const order_id = ref("");
const orderName = ref("");
const data1 = {
  token: token,
  order_id: "",
  page: 1,
  is_cost: 1,
};
// 点击获取详情
const getorder = (row) => {
  if (isclose.value === 2) {
    return false;
  }
  sDetailLeading.value = true;
  // 单选时先清除后选中避免数组混乱
  salesOrderlist.value.refsOrderList.clearSelection();
  salesOrderlist.value.refsOrderList.toggleRowSelection(row);
  data1.order_id = row.order_id;
  order_id.value = row.order_id;
  orderName.value = row.PI_name;
  sInfo.value.orderType = row.orderType;
  sorderInfo.orderType = row.orderType;
  sorderState.value = row.State;
  porderDetails();
};

// 默认订单列表第一条数据详情渲染详情
const getorder1 = () => {
  sDetailLeading.value = true;
  data1.order_id = orderList.value && orderList.value[0].order_id;
  order_id.value = orderList.value && orderList.value[0].order_id;
  orderName.value = orderList.value && orderList.value[0].PI_name;
  sInfo.value.orderType = orderList.value && orderList.value[0].orderType;
  sorderInfo.orderType = orderList.value && orderList.value[0].orderType;
  porderDetails();
};

// 保存原订单信息，编辑保存做校验
const sorderInfo = {
  token: token,
  order_id: "",
  company_id: "",
  Current: "",
  orderType: "",
  payment: {
    config_id: "",
    config_name: "",
  },
  item: [],
};

// 获取订单请求赋值
const porderDetails = () => {
  api.orderDetail(data1).then((res) => {
    sDetailLeading.value = false;
    // 产品列表
    orderDetails.value =
      res.data.list &&
      res.data.list.data.map((item) => {
        item.profit = (
          ((item.price * 1 - item.cost * 1) / item.cost) *
          1 *
          100
        ).toFixed(2);
        item.profit = item.profit == "Infinity" ? 0 : item.profit;
        item.profit = isNaN(item.profit) ? 0 : item.profit;
        return item;
      });
    sorderInfo.item =
      res.data.list &&
      res.data.list.data.map((item) => {
        return {
          order_info_id: item.order_info_id,
          product_id: item.product_id,
          Brand_id: item.Brand_id,
          Brand_name: item.Brand_name,
          product_description_pi: item.product_name_pi,
          product_name_pi: item.product_name_pi,
          weight: item.weight,
          quantity: item.quantity,
          price: item.price,
          leadingtime: item.leadingtime,
          product_condition: item.product_condition,
        };
      });
    orderDetails.value &&
      orderDetails.value.push({
        order_info_id: "", //订单详情id
        product_id: "", //产品ID
        product_name_pi: "", //model
        Brand_id: "", //品牌ID
        Brand_name: "", //品牌
        product_description_pi: "", //描述
        quantity: "", //数量
        price: "", //价格
        product_condition: "", //货况
        leadingtime: "", //交期
        related_doc: "",
        profit: "", //利润
        cost: "", //成本
      });
    // 订单title
    orderTitle.value = res.data.customer && res.data.customer.PI_name;
    CreateTime.value = res.data.customer && res.data.customer.CreateTime;
    sInfo.value.currencyType = res.data.customer && res.data.customer.Current;
    sorderInfo.Current = res.data.customer && res.data.customer.Current;
    // 银行信息
    sInfo.value.paymentvalue =
      res.data.payment && res.data.payment.config_short;
    bankType.value = res.data.payment && res.data.payment.config_name;
    payinfo.value = res.data.payment && res.data.payment.config_value;
    bankID.value = res.data.payment && res.data.payment.config_id;
    sorderInfo.payment.config_id =
      res.data.payment && res.data.payment.config_id;
    sorderInfo.payment.config_name =
      res.data.payment && res.data.payment.config_name;
    sorderInfo.order_id = order_id.value;
    // 供应商信息
    sInfo.value.suppierValue =
      res.data.company && res.data.company.config_short;
    suppierInfo.value = res.data.company && res.data.company.config_value;
    company_id.value = res.data.company && res.data.company.config_id;
    sorderInfo.company_id = res.data.company && res.data.company.config_id;
    // 客户信息
    sInfo.value.userValue = res.data.customer && res.data.customer.firstname;
    userAddress.value = res.data.customer && res.data.customer.address;
    //底部信息
    paymentRecieved.value = res.data.paymentRecieved;
    costs.value = res.data.costs;
    footershippingCost.value = res.data.shippingCost;
    subTotal.value = res.data.subtal;
    discountInfo.value = res.data.customer && res.data.customer.discount_value;
    shippingCostInfo.value =
      res.data.customer && res.data.customer.Shipping_cost;
    paymentFeeInfo.value =
      res.data.customer && res.data.customer.Payment_charge;
    vatInfo.value =
      res.data.customer && res.data.customer.Invoice_shipping_cost;
    totalInfo.value = res.data.customer && res.data.customer.total;
    // 第一个订单产品列表的第一个产品
    product_id.value = res.data.list && res.data.list.data[0].product_id;
    getCurveDiagram();
  });
};
/**获取订单结束 */

/**获取产品曲线数据开始 */
const purchaseChart1 = ref();
const salesList = ref([]);
const purchaseList = ref([]);
const curveDiagramdata = {
  token: token,
  product_id: "",
};
// 默认获取第一个列表第一个产品
const getCurveDiagram = () => {
  curveDiagramdata.product_id = product_id.value;
  api.ordersProductRecord(curveDiagramdata).then((res) => {
    purchaseList.value = res.data.purchase;
    salesList.value = res.data.sale;
    purchaseChart1.value &&
      purchaseChart1.value.init(purchaseList.value, salesList.value);
  });
};
// 点击产品获取
const getProductID = (row) => {
  if (!row.product_id) {
    return false;
  }
  curveDiagramdata.product_id = row.product_id;
  api.ordersProductRecord(curveDiagramdata).then((res) => {
    purchaseList.value = res.data.purchase;
    salesList.value = res.data.sale;
    purchaseChart1.value &&
      purchaseChart1.value.init(purchaseList.value, salesList.value);
  });
};
/**获取产品曲线数据结束 */

/* *搜索获取产品列表开始 */
const modelList = ref([]);
const models = ref([]);
const data2 = {
  token: token,
  kw: "",
};
const getModel = (val) => {
  data2.kw = val;
  utils.debounce(100, () => {
    api.orderModel(data2).then((res) => {
      models.value = res.data.data;
      modelList.value =
        res.data.data &&
        res.data.data.map((item) => {
          let label = item.model;
          let value = item.product_id;
          return { label, value };
        });
    });
  });
};
/* *搜索获取产品列表结束 */

/* *搜索获取产品品牌列表开始 */
const brandList = ref([]);
const biands = ref([]);
let data3 = {
  token: token,
  kw: "",
};
const getBrand = (x) => {
  data3.kw = x;
  utils.debounce(100, () => {
    api.orderBrand(data3).then((res) => {
      biands.value = res.data.data;
      brandList.value =
        res.data.data &&
        res.data.data.map((item) => {
          let label = item.brand_name;
          let value = item.brand_id;
          return { label, value };
        });
    });
  });
};
/* *搜索获取产品品牌列表结束 */

/**获取交期列表开始 */
const leadingList = ref([]);
const getleading = () => {
  api.orderLeading({ token: token }).then((res) => {
    leadingList.value = res.data;
  });
};
/**获取交期列表结束 */

/**获取货况列表开始 */
const conditionList = ref([]);
const getCondition = () => {
  api.orderCondition({ token: token }).then((res) => {
    conditionList.value = res.data;
  });
};
/**获取货况列表结束 */

/**编辑订单保存开始 */
const insertId = (val) => {
  orderDetails.value.forEach((item, index) => {
    if (val.$index === index) {
      item.product_id = val.row.product_name_pi.split("|")[1];
    }
  });
  if (val.$index == orderDetails.value.length - 1) {
    orderDetails.value.push({
      order_info_id: "", //订单详情id
      product_id: "", //产品ID
      product_name_pi: "", //model
      Brand_id: "", //品牌ID
      Brand_name: "", //品牌
      product_description_pi: "", //描述
      weight: "",
      quantity: "", //数量
      price: "", //价格
      product_condition: "", //货况
      leadingtime: "", //交期
      related_doc: "",
      profit: "", //利润
      cost: "", //成本
    });
  }
};

//价格输入事件
const changePrice = (val) => {
  utils.debounce(500, () => {
    orderDetails.value.forEach((item, index) => {
      if (val.$index == index) {
        item.profit = (
          ((item.price * 1 - item.cost * 1) / item.cost) *
          1 *
          100
        ).toFixed(2);
        item.profit = item.profit == "Infinity" ? 0 : item.profit;
        item.profit = isNaN(item.profit) ? 0 : item.profit;
      }
    });
  });
};
const editSave = (sorderState) => {
  if (sorderState !== 1) {
    ElMessage({
      type: "info",
      message: "The order is locked and cannot be edited",
    });
    return false;
  }
  const orderSaves = orderDetails.value.map((item) => {
    return {
      order_info_id: item.order_info_id,
      product_id: item.product_name_pi.split("|")[1]
        ? item.product_name_pi.split("|")[1] * 1
        : item.product_id,
      Brand_id: item.Brand_name.split("|")[1]
        ? item.Brand_name.split("|")[1] * 1
        : item.Brand_id,
      Brand_name: item.Brand_name.split("|")[0],
      product_description_pi: item.product_name_pi.split("|")[0],
      product_name_pi: item.product_name_pi.split("|")[0],
      weight: item.weight,
      quantity: item.quantity,
      price: item.price,
      leadingtime: item.leadingtime,
      product_condition: item.product_condition,
    };
  });
  const editdata = {
    token: token,
    order_id: order_id.value,
    company_id: company_id.value,
    Current: sInfo.value.currencyType,
    orderType: sInfo.value.orderType,
    payment: {
      config_id: bankID.value,
      config_name: bankType.value,
    },
    item: orderSaves,
  };
  editdata.item.pop();
  if (utils.isObjectValueEqual(editdata, sorderInfo)) {
    ElMessage({
      type: "info",
      message: "No change in data",
    });
    return false;
  }
  // 查出插入的数据
  let arr = orderSaves.filter((item) => item.order_info_id === "");
  api.orderEdit(editdata).then((res) => {
    if (res.Status == 0) {
      // 前端更改订单数量
      if (arr.length > 0) {
        orderList.value.forEach((item) => {
          if (item.order_id == order_id.value) {
            item.items = item.items + arr.length;
          }
        });
      }
      porderDetails();
      ElMessage({
        type: "success",
        message: "Save successfully",
      });
    }
  });
};
/**编辑订单保存结束 */

/**创建订单开始 */
const neworderList = ref([]);
const chooseDescr = (product_name_pi) => {
  if (product_name_pi.$index === neworderList.value.length - 1) {
    neworderList.value.push({
      Brand_id: "",
      Brand_name: "",
      cost: "",
      leadingtime: "",
      order_info_id: "",
      price: "",
      product_condition: "",
      product_description_pi: "",
      product_id: "",
      product_name_pi: "",
      profit: "",
      quantity: "",
      related_doc: "",
      weight: "",
    });
  }
};
const orderAdd = () => {
  const itemList = neworderList.value.map((item) => {
    return {
      product_id: item.product_name_pi.split("|")[1], //产品ID
      Brand_id: item.Brand_name.split("|")[1], //品牌ID
      Brand_name: item.Brand_name.split("|")[0], //品牌名
      product_description_pi: item.product_name_pi.split("|")[0],
      product_name_pi: item.product_name_pi.split("|")[0], //产品型号
      quantity: item.quantity, //订单数量
      price: item.price, //订单价格
      leadingtime: item.leadingtime, //交期
      product_condition: item.product_condition, //货况,
      weight: item.weight,
    };
  });
  const orderData = {
    token: token,
    order: {
      fistname: firstName.value ? firstName.value : "",
      lastname: lastName.value ? lastName.value : "",
      customer_info_id: usersID.value, //客户ID
      company_id: company_id.value, //公司ID
      orderType: sInfo.value.orderType, //订单类型
      Current: sInfo.value.currencyType, //货币类型
    },
    payment: {
      config_id: bankID.value, //银行ID
      config_name: bankType.value, //银行名
    },
    item: itemList,
  };
  // 删除最后一条空数据
  orderData.item.pop();
  if (!utils.isObjectNull(orderData)) {
    ElMessage({
      type: "info",
      message: `Please enter the complete information`,
    });
    return false;
  }
  api.ordersAdd(orderData).then((res) => {
    if (res.Status === 0) {
      ElMessage({
        type: "success",
        message: "Successfully created",
      });
      neworderList.value = [];
      resetMethod();
      getOrderList();
    }
  });
};
// 创建订单删除产品
const newDeleteProduct = (info) => {
  if (neworderList.value.length === 1) {
    ElMessage({
      type: "info",
      message: "No data can be deleted",
    });
    return false;
  }
  neworderList.value.splice(info.$index, 1);
};
/**创建订单结束 */

/**删除订单开始 */
const orderDelete = () => {
  if (isclose.value === 2 || orderList.value.length === 0) {
    ElMessage({
      type: "info",
      message: "Unable to delete temporarily",
    });
    return false;
  }
  const deldata = {
    token: token,
    order_id: order_id.value,
  };
  ElMessageBox.confirm("Are you sure to delete this order?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    distinguishCancelAndClose: true,
  })
    .then(() => {
      api.orderDelete(deldata).then((res) => {
        if (res.Status === 0) {
          getOrderList();
          ElMessage({
            type: "success",
            message: "Deleted successfully",
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Deletion failure",
      });
    });
};
/**删除订单结束 */

/**删除订单产品开始 */
const dpdata = {
  token: token,
  order_info_id: "",
};
const deleteProduct = (operation) => {
  if (sorderState.value !== 1) {
    ElMessage({
      type: "info",
      message: "This order cannot be deleted",
    });
    return false;
  }
  if (operation.row.order_info_id) {
    dpdata.order_info_id = operation.row.order_info_id;
    api.orderProductDelete(dpdata).then((res) => {
      if (res.Status === 0) {
        orderDetails.value.splice(operation.$index, 1);
        orderList.value.forEach((item) =>
          item.order_id == order_id.value
            ? (item.items = item.items - 1)
            : item.items
        );
        product_id.value = orderDetails.value[0].product_id;
        getCurveDiagram();
        ElMessage({
          type: "success",
          message: "Deleted successfully",
        });
      }
    });
  } else {
    if (operation.$index !== orderDetails.value.length - 1) {
      orderDetails.value.splice(operation.$index, 1);
      ElMessage({
        type: "success",
        message: "Deleted successfully",
      });
    } else {
      ElMessage({
        type: "info",
        message: "Empty data does not need to be deleted",
      });
    }
  }
};
/**删除订单产品结束 */

/**
 * newOrder 公共方法
 * @param {*确定保存按钮性质} newissave
 * 1、edit保存，2、new保存,3、cp保存, 4、rfq保存,5、qtn保存
 * @param {*确定新建订单性质是否为弹窗} newstat
 * 1为直接创建，0为弹框创建
 */
const publicNew = (newissave, newstat) => {
  if (isclose.value === 1) {
    ElMessageBox.confirm(
      "New data will cause data loss. Determine whether to save the data?",
      "Warning",
      {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        distinguishCancelAndClose: true,
      }
    )
      .then(() => {
        orderList.value.length == 0 ? "" : editSave(sorderState.value);
        // 订单title
        orderTitle.value = "";
        CreateTime.value = "";
        sInfo.value.orderType = "";
        sInfo.value.currencyType = "";
        // 银行信息
        sInfo.value.paymentvalue = "";
        payinfo.value = "";
        bankID.value = "";
        bankType.value = "";
        // 供应商信息
        sInfo.value.suppierValue = "";
        suppierInfo.value = "";
        company_id.value = "";
        // 客户信息
        sInfo.value.userValue = "";
        userAddress.value = "";
        usersID.value = "";
        // 点击新建订单弹窗功能关闭
        isclose.value = 2;
        // 切换为订单新增表格
        state1.value = true;
        // 更改保存状态为新建订单保存 1、edit保存，2、new保存,3、cp保存, 4、rfq保存,5、qtn保存
        issave.value = newissave;
        // 更改订单状态为可编辑，解锁录单下拉框
        sorderState.value = 1;
        // 1创建列表插入一条空数据，0赋值后在插入
        if (newstat === 1) {
          // 给创建列表插入一条数据
          neworderList.value.push({
            Brand_id: "",
            Brand_name: "",
            cost: "",
            leadingtime: "",
            order_info_id: "",
            price: "",
            product_condition: "",
            product_description_pi: "",
            product_id: "",
            product_name_pi: "",
            profit: "",
            quantity: "",
            related_doc: "",
          });
        } else {
          // 创建列表重新赋值
          neworderList.value = selectList.value;
          neworderList.value.push({
            Brand_id: "",
            Brand_name: "",
            cost: "",
            leadingtime: "",
            order_info_id: "",
            price: "",
            product_condition: "",
            product_description_pi: "",
            product_id: "",
            product_name_pi: "",
            profit: "",
            quantity: "",
            related_doc: "",
          });
        }
      })
      .catch(() => {
        sorderState.value =
          orderList.value &&
          orderList.value.filter((item) => item.order_id == order_id.value)[0]
            .State;
        // 点击取消后恢复弹窗
        isclose.value = 1;
        ElMessage({
          type: "info",
          message: "Save cancelled",
        });
      });
  }
};

/**
 * 弹框neworder 公共方法
 * @param {* 创建列表} neworderList
 * @param {* 组件名} componentName
 * @param {* 弹框左列表} leftList
 * @param {* 弹框右列表} rightList
 *
 */
const publicNeworder = (neworderList, componentName, leftList, rightList) => {
  const item = neworderList.value.map((item) => {
    return {
      product_id:
        item.product_name_pi.split("|").length === 2
          ? item.product_name_pi.split("|")[1] * 1
          : item.product_id * 1, //产品ID
      Brand_id:
        item.Brand_name.split("|").length === 2
          ? item.Brand_name.split("|")[1] * 1
          : item.Brand_id * 1, //品牌ID
      Brand_name:
        item.Brand_name.split("|").length === 2
          ? item.Brand_name.split("|")[0]
          : item.Brand_name, //品牌名
      product_description_pi:
        item.product_name_pi.split("|").length === 2
          ? item.product_name_pi.split("|")[0]
          : item.product_name_pi,
      product_name_pi:
        item.product_name_pi.split("|").length === 2
          ? item.product_name_pi.split("|")[0]
          : item.product_name_pi, //产品型号
      quantity: item.quantity, //订单数量
      weight: item.weight,
      price: item.price, //订单价格
      leadingtime: item.leadingtime, //交期
      product_condition: item.product_condition, //货况
    };
  });
  item.pop();
  const NewSavedata = {
    token: token,
    order: {
      fistname: firstName.value,
      lastname: lastName.value,
      customer_info_id: usersID.value, //客户ID
      company_id: company_id.value, //公司ID
      Current: sInfo.value.currencyType, //货币类型
      orderType: sInfo.value.orderType, //订单类型
    },
    payment: {
      config_id: bankID.value, //银行ID
      config_name: bankType.value, //银行名
    },
    item: item,
  };
  if (!utils.isObjectNull(NewSavedata)) {
    ElMessage({
      type: "info",
      message: `Please enter the complete information`,
    });
    return false;
  }
  api.ordersAdd(NewSavedata).then((res) => {
    if (res.Status === 0) {
      ElMessage({
        type: "success",
        message: "Successfully created",
      });
      // 重置相关内容
      if (componentName.value.rfqID) {
        componentName.value.rfqID = "";
      } else if (componentName.value.qtnID) {
        componentName.value.qtnID = "";
      } else if (componentName.value.orderID1) {
        componentName.value.orderID1 = "";
      }
      neworderList.value = [];
      leftList.value = [];
      rightList.value = [];
      // 重置刷新
      resetMethod();
      getOrderList();
    }
  });
};

/**
 * qtn rfq 保存公共方法
 * @param {*右侧列表} rightlist
 * @param {*组件名} componentName
 * @param {*左侧列表} leftList
 * @param {*id} id
 */
const publicSave = (rightlist, componentName, leftList, id) => {
  const item = rightlist.value.map((item) => {
    return {
      order_id: id,
      inquiry_id: item.inquiry_id ? item.inquiry_id : 0,
      inquiry_item_purchase_price_id: item.inquiry_item_purchase_price_id
        ? item.inquiry_item_purchase_price_id
        : 0,
      product_id: item.product_id,
      model: item.product_name_pi,
      brand_id: item.Brand_id,
      brand_name: item.Brand_name,
      product_condition: item.product_condition,
      quantity: item.quantity,
      price: item.price,
      leadingtime: item.leadingtime,
      weight: item.weight,
    };
  });
  const data = {
    token: store.token,
    isNew: 0,
    order: "",
    item: item,
  };
  if (data.item.length === 0) {
    ElMessage({
      type: "info",
      message: "There is no data for now. Select the data and submit ",
    });
    return false;
  }
  api.orderFromRfqSave(data).then((res) => {
    if (res.Status === 0) {
      // 保存后更改主页内容
      data1.order_id = id;
      orderList.value.forEach((item) =>
        item.order_id == id
          ? (item.items = item.items + rightlist.value.length)
          : item.items
      );
      porderDetails();
      // 重置
      if (componentName.value.rfqID) {
        componentName.value.rfqID = "";
      } else if (componentName.value.qtnID) {
        componentName.value.qtnID = "";
      }
      componentName.value.open = false;
      leftList.value = [];
      rightlist.value = [];
      ElMessage({
        type: "success",
        message: "Successful replication",
      });
    }
  });
};

// 公用复选框方法
const selectList = ref([]);
const SelectionMethod = (val) => {
  selectList.value = val;
};

/*** 公共重置方法*/
const resetMethod = () => {
  // 恢复默认编辑保存
  issave.value = 1;
  // 保存后，恢复订单产品表格
  state1.value = false;
  // 恢复新建弹窗功能
  isclose.value = 1;
};

/**订单相关的弹窗开始 */
const clearance = ref();
const copy = ref();
const fromrfq = ref();
const fromqtn = ref();
const exportPI = ref();
const placeanOrder = ref();
const deliverGoods = ref();
// 切换新增订单
const state1 = ref(false);
// 控制产品列表大小
const state = ref(true);
const change = () => {
  state.value = !state.value;
};
// 控制新建弹窗是否开启，设置点击后再次点击不在弹窗
let isclose = ref(1);
// 做判断 默认1为订单编辑保存
let issave = ref(1);
const open = (x) => {
  // new
  if (x === 1) {
    getleading();
    getCondition();
    publicNew(2, 1);
  }
  // copy to order
  else if (x === 2) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    selectList.value = [];
    copy.value.dialogopen();
  }
  // from rfq
  else if (x === 3) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    selectList.value = [];
    fromrfq.value.dialogopen();
    getrfqProductList();
  }
  // fromqtn
  else if (x === 4) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    selectList.value = [];
    fromqtn.value.dialogopen();
    getqtnProductList();
  }
  // clearance
  else if (x === 5) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    clearance.value.dialogopen();
    getClearList();
  }
  // placeAnOrder
  else if (x === 7) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    placeanOrder.value.dialogopen();
    getOrderedList();
  }
  // DeliverGoods
  else if (x === 8) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    getOrderInfos();
    deliverGoods.value.dialogopen();
  }
  // export PI
  else if (x === 9) {
    if (isclose.value === 2) {
      ElMessage({
        type: "info",
        message: "New order cannot use popover",
      });
      return false;
    }
    exportPI.value.dialogopen();
    getExportPI();
  }
  // save
  else if (x === 6) {
    // 订单编辑保存
    if (issave.value === 1) {
      if (orderList.value.length === 0) {
        ElMessage({
          type: "info",
          message: "No data, can't save",
        });
        return false;
      }
      editSave(sorderState.value);
    }
    // 新建订单
    else if (issave.value === 2) {
      orderAdd();
    }
    // copy to order 新建订单保存
    else if (issave.value === 3) {
      copyNeworderSave();
    }
    // from rfq
    else if (issave.value === 4) {
      rfqneworderSave();
    }
    // from qtn
    else if (issave.value === 5) {
      alert("from qtn ");
      qtnneworderSave();
    }
  }
};
/**订单相关的弹窗结束 */
const data4 = {
  token: token,
  kw: "",
};
// 订单来源的弹窗orderID列表公用
const orderidList = ref([]);
// 搜索订单id列表，弹窗公用
const getOrderid = (val) => {
  data4.kw = val;
  utils.debounce(100, () => {
    api.oederidList(data4).then((res) => {
      orderidList.value = res.data.data && res.data.data;
    });
  });
};
// 弹窗公用删除列表方法
const deleteSolo = (val, title) => {
  if (title == "copy") {
    rightOrder.value.splice(val.$index, 1);
  } else if (title == "rfq") {
    rfqnewList.value.splice(val.$index, 1);
  } else {
    qtnnewList.value.splice(val.$index, 1);
  }
};
// 弹窗公用删除回调函数
const closeInfo = (val) => {
  if (val === 1) {
    leftOrder.value = [];
    rightOrder.value = [];
  } else if (val === 2) {
    rfqnewList.value = [];
  } else if (val === 3) {
    qtnnewList.value = [];
  } else if (val === 5) {
    exportPurList.value = [];
  }
};
/**copt to order 弹窗开始 */

// 右侧订单产品详情列表
const copydata = {
  token: token,
  order_id: "",
};
const leftOrder = ref([]);
const getorderProductList = (ID) => {
  copydata.order_id = ID;
  api.copyOrder(copydata).then((res) => {
    leftOrder.value = res.data.item && res.data.item;
  });
};
// 左侧订单产品详情列表
const rightOrder = ref([]);
// 复制到订单
const copyOrder = () => {
  if (leftOrder.value.length == 0) {
    ElMessage({
      type: "info",
      message: "No data yet",
    });
    return false;
  }
  rightOrder.value = selectList.value;
};
// 保存
const copyOrderSave = (id) => {
  const cplist = rightOrder.value.map((item) => {
    return {
      product_id: item.product_id, //产品ID
      Brand_id: item.Brand_id, //品牌ID
      Brand_name: item.Brand_name, //品牌名
      product_name_pi: item.product_name_pi, //产品名（model）
      quantity: item.quantity, //数量
      price: item.price, //价格
      leadingtime: item.leadingtime, //交期
      product_condition: item.product_condition,
      weight: item.weight,
    };
  });
  const cpdata = {
    token: token,
    order_id: "",
    item: cplist,
  };
  if (cpdata.item.length === 0) {
    ElMessage({
      type: "info",
      message: "There is no data for now. Select the data and submit ",
    });
    return false;
  }
  cpdata.order_id = id;
  api.orderSaveCopyToOrder(cpdata).then((res) => {
    if (res.Status === 0) {
      // 保存后更改主页内容
      data1.order_id = id;
      orderList.value.forEach((item) =>
        item.order_id == id
          ? (item.items = item.items + rightOrder.value.length)
          : item.items
      );
      porderDetails();
      // 重置弹框
      copy.value.orderID1 = "";
      copy.value.open = false;
      leftOrder.value = [];
      rightOrder.value = [];
      ElMessage({
        type: "success",
        message: "Successful replication",
      });
    }
  });
};
// cp 新建订单
const newOrder = () => {
  copy.value.open = false;
  publicNew(3, 0);
};
// copy to order 新建保存
const copyNeworderSave = () => {
  publicNeworder(neworderList, copy, leftOrder, rightOrder);
};
/**copt to order 弹窗结束 */

/** from rfq 弹窗开始 */
const rfqdata = {
  token: store.token,
  inquiry_id: "",
  page: 1,
};
// 获取rfq产品列表
const rfqProductList = ref([]);
const rfqPublic = () => {
  api.orderFromRfq(rfqdata).then((res) => {
    rfqProductList.value =
      res.data.list &&
      res.data.list.data.map((item) => {
        item.price = (item.price * 1).toFixed(2);
        item.weight = (item.weight * 1).toFixed(2);
        return item;
      });
  });
};
const getrfqProductList = (val) => {
  if (!!val) {
    rfqdata.inquiry_id = val;
    rfqdata.page = 1;
    utils.debounce(1000, () => {
      rfqPublic();
    });
  } else {
    rfqdata.inquiry_id = "";
    rfqdata.page = 1;
    rfqPublic();
  }
};
// 清除方法
const clearRfq = () => {
  rfqdata.inquiry_id = "";
  rfqPublic();
};
//上拉加载
const rfqlength = ref(1);
const getrfqProductList1 = () => {
  if (rfqProductList.value.length == 0 || rfqlength.value == 0) return false;
  rfqdata.page++;
  api.orderFromRfq(rfqdata).then((res) => {
    rfqlength.value = res.data.length;
    rfqProductList.value = [
      ...rfqProductList.value,
      ...(res.data.length !== 0
        ? res.data.list.data.map((item) => {
            item.price = (item.price * 1).toFixed(2);
            item.weight = (item.weight * 1).toFixed(2);
            return item;
          })
        : []),
    ];
  });
};

// add按钮方法
const rfqnewList = ref([]);
const rfqAdd = () => {
  if (rfqProductList.value.length == 0) {
    ElMessage({
      type: "info",
      message: "No data yet",
    });
    return false;
  }
  rfqnewList.value = selectList.value;
};
// rfq保存按钮方法
const rfqSave = (id) => {
  publicSave(rfqnewList, fromrfq, rfqProductList, id);
};
// rfq 新建订单
const rfqnewOrder = () => {
  fromrfq.value.open = false;
  publicNew(4, 0);
};

// rfq新建订单保存
const rfqneworderSave = () => {
  publicNeworder(neworderList, fromrfq, rfqProductList, rfqnewList);
};
/** from rfq 弹窗结束 */

/**from qtn 开始 */
const qtndata = {
  token: store.token,
  inquiry_id: "",
  page: 1,
};
// 获取qtn信息列表
const qtnProductList = ref([]);
const qtnPublic = () => {
  api.orderFromQtn(qtndata).then((res) => {
    qtnProductList.value =
      res.data.list &&
      res.data.list.data.map((item) => {
        item.price = (item.price * 1).toFixed(2);
        item.weight = (item.weight * 1).toFixed(2);
        return item;
      });
  });
};
const getqtnProductList = (val) => {
  if (!!val) {
    qtndata.inquiry_id = val;
    qtndata.page = 1;
    utils.debounce(1000, () => {
      qtnPublic();
    });
  } else {
    qtndata.inquiry_id = "";
    qtndata.page = 1;
    qtnPublic();
  }
};
const clearQtn = () => {
  qtndata.inquiry_id = "";
  qtnPublic();
};
// 上拉加载
const qtnresdata = ref("");
const getqtnProductList1 = () => {
  if (qtnProductList.value.length == 0 || qtnresdata.value == "暂无数据")
    return false;
  qtndata.page++;
  api.orderFromQtn(qtndata).then((res) => {
    qtnresdata.value = res.data;
    qtnProductList.value = [
      ...qtnProductList.value,
      ...(!!res.data.list
        ? res.data.list.data.map((item) => {
            item.price = (item.price * 1).toFixed(2);
            item.weight = (item.weight * 1).toFixed(2);
            return item;
          })
        : []),
    ];
  });
};
// add 方法
const qtnnewList = ref([]);
const qtnAdd = () => {
  if (qtnProductList.value.length == 0) {
    ElMessage({
      type: "info",
      message: "No data yet",
    });
    return false;
  }
  qtnnewList.value = selectList.value;
};
// qtn save
const qtnSave = (id) => {
  publicSave(qtnnewList, fromqtn, qtnProductList, id);
};
// qtn neworder
const qtnnewOrder = () => {
  fromqtn.value.open = false;
  publicNew(5, 0);
};
// qtn Newsave
const qtnneworderSave = () => {
  publicNeworder(neworderList, fromqtn, qtnProductList, qtnnewList);
};
/**from qtn 结束 */

/**Clearance 开始 */
const clearList = ref([]);

const totalAmount = ref("");
const declareAmount = ref();
// 获取clear列表
const getClearList = () => {
  const cleardata = {
    token: token,
    order_id: order_id.value,
  };
  api.orderClearance(cleardata).then((res) => {
    clearList.value = res.data.list;
    totalAmount.value = res.data.order_total;
    declareAmount.value = res.data.declare_total.replace(/,/g, "") * 1;
  });
};

// 获取范围内的随机清关价格
let isrelease = ref(0);
const getnumber = (x, Number) => {
  isrelease.value = 1;
  let max = Number;
  let min;
  if (x === "Value") {
    clearance.value.percentage = "";
    min = Number * 0.8;
    let num = (Math.random() * (max - min) + min).toFixed(2);
    declareAmount.value = num * 1;
  } else if (x === "<500") {
    clearance.value.percentage = "";
    clearance.value.clearMoney = "";
    min = 400;
    let num = (Math.random() * (max - min) + min).toFixed(2);
    declareAmount.value = num * 1;
  } else if (x === "<700") {
    clearance.value.percentage = "";
    clearance.value.clearMoney = "";
    min = 500;
    let num = (Math.random() * (max - min) + min).toFixed(2);
    declareAmount.value = num * 1;
  } else if (x === "<800") {
    clearance.value.percentage = "";
    clearance.value.clearMoney = "";
    min = 700;
    let num = (Math.random() * (max - min) + min).toFixed(2);
    declareAmount.value = num * 1;
  } else {
    utils.debounce(1000, () => {
      clearance.value.clearMoney = "";
      declareAmount.value = totalAmount.value.replace(/,/g, "") * 1 * (x / 100);
    });
  }
};

// 清关订单保存
const ClearanceSave = () => {
  const invoice = clearList.value.map((item) => {
    return {
      order_info_id: item.order_info_id,
      product_name_invoice: item.product_description_pi,
      product_description_invoice: item.product_description_invoice,
      price_declare_invoice: clearance.value.calculatePrice(
        totalAmount.value,
        item.price * 1
      ),
    };
  });
  const clearData = {
    token: token,
    invoice: invoice,
  };
  api.orderClearanceSave(clearData).then((res) => {
    isrelease.value = 0;
    if (res.Status === 0) {
      clearance.value.open = false;
      clearance.value.clearMoney = "";
      clearance.value.percentage = "";
      ElMessage({
        type: "success",
        message: "Save successfully",
      });
    }
  });
};
/**Clearance 结束 */

/***Expost PI开始 */
const imgList = ref([]);
const exportPImodels = ref([]);
const capitalTotal = ref({});
const invoiceInfo = ref({});
// 获取excel模板
const excelids = ref([]);
const getExportPI = () => {
  const exportData = {
    token: token,
    order_id: order_id.value,
  };
  api.ordersClearanceData(exportData).then((res) => {
    exportPImodels.value =
      res.data &&
      res.data.item.map((item) => {
        return {
          "Model No": item.product_name_pi,
          "Commodity&description": item.product_description_pi,
          "Qty(PCS)": item.quantity,
          "Unit Price(USD)": utils.currencType("USD") + item.price,
          "Amount(USD)": utils.currencType("USD") + item.price,
        };
      });
    capitalTotal.value = res.data.total && res.data.total;
    invoiceInfo.value = res.data.order && res.data.order;
  });
  api.ordersExcelTemplate({ token: store.token }).then((res) => {
    excelids.value = res.data;
  });
};
/***Expost PI结束 */

/***Place an Order开始 **/
const PlaceList = ref([]);
// 获取采购员列表
const buyerList = ref([]);
const buyerdata = {
  token: token,
  kw: "",
  group: 2,
  page: 1,
};
const getBuyerList = (val) => {
  buyerdata.kw = val;
  utils.debounce(500, () => {
    api.ordersConfigGetUser(buyerdata).then((res) => {
      buyerList.value =
        res.data.data &&
        res.data.data.map((item) => {
          item.id = item.id * 1;
          return item;
        });
    });
  });
};
const orderedList = ref([]);
const orderedData = {
  token: token,
  item_ids: [],
};
const qtySum = ref(0);
const hqtySum = ref(0);
const getOrderedList = () => {
  PlaceList.value = orderDetails.value;
  PlaceList.value[PlaceList.value.length - 1].order_info_id == ""
    ? PlaceList.value.pop()
    : "";
  let item_ids = orderDetails.value.map((item) => {
    return {
      order_info_id: item.order_info_id,
    };
  });
  orderedData.item_ids = item_ids;

  // 获取已订货数据组合弹窗数据
  api.ordersPurchaseTesk(orderedData).then((res) => {
    // 采购集合
    orderedList.value = res.data.buy_number && res.data.buy_number;
    // 弹窗数据
    PlaceList.value = PlaceList.value.map((item) => {
      item.purcharse = "";
      item.purcharse1 = "";
      item.pqty = "";
      item.hqty = orderedList.value.filter((item1) => {
        return item.order_info_id == item1.order_info_id;
      });
      item.hqty = item.hqty[0] && item.hqty[0].Qtynumber;
      item.hqty = typeof item.hqty == "undefined" ? 0 : item.hqty;
      item.purList =
        res.data.list &&
        res.data.list.filter((row) => row.order_info_id == item.order_info_id);
      return item;
    });
    qtySum.value = PlaceList.value.reduce((sum, item) => {
      return (sum += item.quantity);
    }, 0);
    hqtySum.value = PlaceList.value.reduce((sum, item) => {
      return (sum += item.hqty);
    }, 0);
    setTimeout(() => {
      toggleSelection1(
        PlaceList.value.filter((item) => item.quantity * 1 > item.hqty * 1)
      );
    });
  });
};
// 统一修改采购，分别存放采购名和id，拿参数时判断获取
const changePur = (val) => {
  PlaceList.value = PlaceList.value.map((item) => {
    item.purcharse = val.split("|")[1];
    item.purcharse1 = val.split("|")[0] * 1;
    return item;
  });
  setTimeout(() => {
    toggleSelection1(
      PlaceList.value.filter((item) => item.quantity - item.hqty > 0)
    );
  });
};
const allList1 = [];
const changeInput1 = (val) => {
  utils.debounce(500, () => {
    allList1.push(val);
    setTimeout(() => {
      toggleSelection1(allList1);
    });
    PlaceList.value = PlaceList.value.map((item) => {
      if (item.pqty * 1 > item.quantity * 1 - item.hqty * 1) {
        ElMessage({
          type: "info",
          message: "Insufficient procurement",
        });
        item.pqty = item.quantity - item.hqty;
      }
      return item;
    });
  });
};
// 切换订货类型
const changeRadio = (val) => {
  val == 2
    ? PlaceList.value.map((item) => {
        item.purcharse = "";
        item.purcharse1 = "";
        return item;
      })
    : "";
  // 全选时默认选中未完全发货的数据
  val == 1
    ? toggleSelection1(
        PlaceList.value.filter((item) => item.quantity - item.hqty > 0)
      )
    : toggleSelection1();
};
// 全选方法
const toggleSelection1 = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      placeanOrder.value.multipleTableRef.toggleRowSelection(row, true);
    });
  } else {
    placeanOrder.value.multipleTableRef.clearSelection();
  }
};
const allList = ref([]);
const selectAll = (val) => {
  allList.value = val;
};

const takeAddData = {
  token: token,
  item: [],
};
// 订货任务
const purchaseOrderteskAdd = (val) => {
  let item;
  if (qtySum.value == hqtySum.value) {
    ElMessage({
      type: "info",
      message: "Orders placed cannot be placed",
    });
    return false;
  }
  if (val == 1) {
    item = allList.value.map((item) => {
      return {
        order_info_id: item.order_info_id,
        Purchaser_id:
          typeof item.purcharse == "string" ? item.purcharse1 : item.purcharse,
        quantity: item.quantity - item.hqty,
      };
    });
  } else {
    item = allList.value.map((item) => {
      return {
        order_info_id: item.order_info_id,
        Purchaser_id: item.purcharse,
        quantity: item.pqty * 1,
      };
    });
  }
  takeAddData.item = item;
  const sum = allList.value.reduce((sum, item) => {
    return (sum += item.quantity - item.hqty);
  }, 0);
  const sumed = takeAddData.item.reduce((sum, item) => {
    return (sum += item.quantity);
  }, 0);
  api.purchaseOrderteskAdd(takeAddData).then((res) => {
    if (res.Status === 0) {
      placeanOrder.value.purcharse = "";
      placeanOrder.value.radio = "1";
      placeanOrder.value.open = false;
      porderDetails();
      orderList.value.forEach((item) => {
        if (item.order_id == order_id.value) {
          if (sum == sumed) {
            item.state_text = "预订货";
            item.State = 2;
          } else {
            item.state_text = "部分订货";
            item.State = 8;
          }
        }
      });
      ElMessage({
        type: "success",
        message: "Successful order",
      });
    }
  });
};
/***Place an Order结束 **/

/***Deliver Goods开始 **/
const orderInfoList = ref([]);
const orderInfodata = {
  token: token,
  order: [],
};
const getOrderInfos = () => {
  orderInfodata.order = selectList.value.map((item) => {
    return { order_id: item.order_id };
  });
  api.ordersGetAddShiptaskData(orderInfodata).then((res) => {
    orderInfoList.value =
      res.data &&
      res.data.map((item) => {
        item.pqty = item.OrdertaskQty - item.ShipQty;
        item.purchaserInfo = item.purchaser.join("&");
        return item;
      });
    setTimeout(() => {
      toggleSelection(
        orderInfoList.value.filter((item) => item.quantity - item.ShipQty > 0)
      );
    });
  });
};
// 切换全选和部分发货
const changeRadio1 = (x) => {
  x == 1
    ? toggleSelection(
        orderInfoList.value.filter((item) => item.quantity - item.ShipQty > 0)
      )
    : toggleSelection();
};
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      deliverGoods.value.deliverList.toggleRowSelection(row, true);
    });
  } else {
    deliverGoods.value.deliverList.clearSelection();
  }
};
// 输入事件
const goodsList1 = [];
const changeInput = (val) => {
  utils.debounce(500, () => {
    goodsList1.push(val);
    setTimeout(() => {
      toggleSelection(goodsList1);
    });
    orderInfoList.value = orderInfoList.value.map((item) => {
      if (item.pqty * 1 > item.quantity * 1 - item.ShipQty * 1) {
        ElMessage({
          type: "info",
          message: "Insufficient procurement",
        });
        item.pqty = item.quantity - item.ShipQty;
      }
      return item;
    });
  });
};
// 选项框值发生改变时触发，
const goodsAllList = ref([]);
const goodSelectAll = (val) => {
  goodsAllList.value = val;
};
const goodsAddData = {
  token: token,
  item: [],
};
// 发请求
const goodsAdd = (val) => {
  let items;
  if (val == 1) {
    items = goodsAllList.value.map((item) => {
      return {
        order_info_id: item.order_info_id,
        quantity: item.OrdertaskQty * 1 - item.ShipQty * 1,
      };
    });
  } else {
    items = goodsAllList.value.map((item) => {
      return {
        order_info_id: item.order_info_id,
        quantity: item.pqty * 1,
      };
    });
  }
  goodsAddData.item = items;
  const statelist = goodsAllList.value.map((item) => {
    return { quantity: item.OrdertaskQty * 1 - item.ShipQty * 1 };
  });
  const sum = statelist.reduce((sum, item) => {
    return sum + item.quantity;
  }, 0);
  const sumed = goodsAddData.item.reduce((sum, item) => {
    return sum + item.quantity;
  }, 0);
  api.ordersAddShiptask(goodsAddData).then((res) => {
    if (res.Status == 0) {
      orderList.value.forEach((item) => {
        if (item.order_id == order_id.value) {
          if (sum == sumed) {
            item.state_text = "已分配发货";
            item.State = 6;
          } else {
            item.state_text = "部分分配发货";
            item.State = 5;
          }
        }
      });
      deliverGoods.value.radio = "1";
      deliverGoods.value.open = false;
      porderDetails();
      ElMessage({
        type: "success",
        message: "Successful delivery",
      });
    }
  });
};
/***Deliver Goods结束 **/

/** 底部支付信息开始 */
const paymentRecieved = ref([]);
const costs = ref([]);
const footershippingCost = ref([]);
const subTotal = ref("");
const discountInfo = ref("");
const shippingCostInfo = ref("");
const paymentFeeInfo = ref("");
const vatInfo = ref("");
const totalInfo = ref("");
/**底部支付信息结束 */

/**获取底部弹框子组件方法开始 */
const discount = ref();
const vat = ref();
const shippingCost = ref();
const paymentfee = ref();

// 底部弹框保存公共参数
const publicData = {
  token: token,
  order_id: "",
  type: "",
  fee: "",
};
/** Discount 弹框开始*/
const calculation = () => {
  utils.debounce(1000, () => {
    let percentage = discount.value.ratio / 100;
    discount.value.CalculatedNumber = (subTotal.value * percentage).toFixed(2);
  });
};
// 保存数值
const discountSave = (type) => {
  publicData.order_id = order_id.value;
  publicData.type = type;
  publicData.fee = discount.value.CalculatedNumber * 1;
  api.ordersServiceCharge(publicData).then((res) => {
    if (res.Status === 0) {
      discountInfo.value = discount.value.CalculatedNumber;
      totalInfo.value =
        discountInfo.value * 1 +
        shippingCostInfo.value * 1 +
        paymentFeeInfo.value * 1 +
        vatInfo.value * 1;
      discount.value.open = false;
      discount.value.ratio = "";
      discount.value.CalculatedNumber = "";
      ElMessage({
        type: "success",
        message: "Save successfully",
      });
    }
  });
};
/** Discount 弹框结束*/

/**shippingCost 弹框开始 */
const shippingCostSave = (type) => {
  publicData.order_id = order_id.value;
  publicData.type = type;
  publicData.fee = shippingCost.value.ShippingCost * 1;
  api.ordersServiceCharge(publicData).then((res) => {
    if (res.Status === 0) {
      shippingCostInfo.value = shippingCost.value.ShippingCost;
      totalInfo.value =
        discountInfo.value * 1 +
        shippingCostInfo.value * 1 +
        paymentFeeInfo.value * 1 +
        vatInfo.value * 1;
      shippingCost.value.open = false;
      shippingCost.value.ShippingCost = "";
      ElMessage({
        type: "success",
        message: "Save successfully",
      });
    }
  });
};
/**shippingCost 弹框结束 */

/**Vat 弹框开始 */
const vatcalculation = () => {
  utils.debounce(1000, () => {
    let percentage = vat.value.ratio / 100;
    vat.value.CalculatedNumber = (subTotal.value * percentage).toFixed(2);
  });
};
// 保存
const vatSave = (type) => {
  publicData.order_id = order_id.value;
  publicData.type = type;
  publicData.fee = vat.value.CalculatedNumber * 1;
  api.ordersServiceCharge(publicData).then((res) => {
    if (res.Status === 0) {
      vatInfo.value = vat.value.CalculatedNumber;
      totalInfo.value =
        discountInfo.value * 1 +
        shippingCostInfo.value * 1 +
        paymentFeeInfo.value * 1 +
        vatInfo.value * 1;
      vat.value.open = false;
      vat.value.ratio = "";
      vat.value.CalculatedNumber = "";
      ElMessage({
        type: "success",
        message: "Save successfully",
      });
    }
  });
};
/**Vat 弹框结束 */

/**PaymentFee 弹框开始 */
const paymentFeecompute = () => {
  paymentfee.value.CalculatedNumber = (
    subTotal.value * paymentfee.value.ratio
  ).toFixed(2);
};
const paymentFeeSave = (type) => {
  publicData.order_id = order_id.value;
  publicData.type = type;
  publicData.fee = paymentfee.value.CalculatedNumber * 1;
  api.ordersServiceCharge(publicData).then((res) => {
    if (res.Status === 0) {
      paymentFeeInfo.value = paymentfee.value.CalculatedNumber;
      totalInfo.value =
        discountInfo.value * 1 +
        shippingCostInfo.value * 1 +
        paymentFeeInfo.value * 1 +
        vatInfo.value * 1;
      paymentfee.value.open = false;
      paymentfee.value.CalculatedNumber = "";
      ElMessage({
        type: "success",
        message: "Save successfully",
      });
    }
  });
};
/**PaymentFee 弹框结束 */

/***销售单开启底部弹框开始 */
const open1 = (x) => {
  if (x === 1) {
    discount.value.dialogopen();
  } else if (x === 2) {
    shippingCost.value.dialogopen();
  } else if (x === 3) {
    paymentfee.value.dialogopen();
  } else if (x === 4) {
    vat.value.dialogopen();
  }
};
/***销售单开启底部弹框结束 */

/**获取底部弹框子组件方法结束 */

/********************************销售单逻辑结束******************************************** */

/********************************采购单逻辑开始******************************************** */
/*** 获取采购任务开始**/
const takeLeading = ref(true);
const takeList = ref();
const purcharseTakeList = ref([]);
const purTitle = ref("");
const purTime = ref("");
const takedata = {
  token: token,
  page: "",
  PI_name: "",
  pageSize: 20,
  orderby: {
    State: "asc", //状态排序 desc-倒序，asc-顺序
    purchaseorder_id: "desc", //根据添加时间排序 desc-倒序，asc-顺序
    PI_name: "desc", //根据订单号排序
  },
};
const getpurTakeList = () => {
  porderRequest();
};
// 上拉加载
const purlength = ref(1);
const refreshPurTakeList = () => {
  if (purcharseTakeList.value.length == 0 || purlength.value == 0) return false;
  takedata.page++;
  api.purchaseOrderTakeList(takedata).then((res) => {
    purlength.value = res.data.data && res.data.data.length;
    purcharseTakeList.value = [
      ...purcharseTakeList.value,
      ...(res.data.data && res.data.data),
    ];
    setTimeout(() => {
      takeList.value.takeOrderList.toggleRowSelection(
        purcharseTakeList.value.filter(
          (item) => item.purchaseordertesk_id == purchaseordertesk_id.value
        )[0],
        true
      );
    });
  });
};
const porderRequest = () => {
  takedata.page = 1;
  api.purchaseOrderTakeList(takedata).then((res) => {
    takeLeading.value = false;
    purcharseTakeList.value = res.data.data && res.data.data;
    setTimeout(() => {
      takeList.value.takeOrderList &&
        takeList.value.takeOrderList.toggleRowSelection(
          purcharseTakeList.value ? purcharseTakeList.value[0] : [],
          true
        );
    });
    getPurTake1();
  });
};

// 获取任务详情
const takeDetailLeading = ref(false);
const takeDetailList = ref([]);
let purchaseordertesk_id = ref("");
let purchaserPeople = "";
const takeDetaildata = {
  token: token,
  purchase_tesk_ids: [],
};
//点击
const getPurTake = (row) => {
  if (allocationState.value) {
    return false;
  }
  takeDetailLeading.value = true;
  // 单选时先清除后选中避免数组混乱
  takeList.value.takeOrderList.clearSelection();
  takeList.value.takeOrderList.toggleRowSelection(row);
  purchaseordertesk_id.value = row.purchaseordertesk_id;
  takeDetaildata.purchase_tesk_ids = [
    { purchaseordertesk_id: purchaseordertesk_id.value },
  ];
  purchaserPeople = row.purchaser;
  purTitle.value = row.PI_name;
  purTime.value = new Date(row.create_time.replace(/-/g, "/")).toDateString();
  takeDetails();
};
// 默认
const getPurTake1 = () => {
  takeDetailLeading.value = true;
  purchaseordertesk_id.value =
    purcharseTakeList.value && purcharseTakeList.value[0].purchaseordertesk_id;
  takeDetaildata.purchase_tesk_ids = [
    { purchaseordertesk_id: purchaseordertesk_id.value },
  ];
  purchaserPeople =
    purcharseTakeList.value && purcharseTakeList.value[0].purchaser;
  purTitle.value =
    purcharseTakeList.value && purcharseTakeList.value[0].PI_name;
  purTime.value =
    purcharseTakeList.value &&
    new Date(
      purcharseTakeList.value[0].create_time.replace(/-/g, "/")
    ).toDateString();
  takeDetails();
};
const takeDetails = () => {
  api.purchaseOrderteskDetail(takeDetaildata).then((res) => {
    takeDetailLeading.value = false;
    takeDetailList.value =
      res.data.list &&
      res.data.list.data.map((item) => {
        // 分配存放采购id
        item.purcharse = "";
        // 分配采购数量
        item.quantity = "";
        // 详情显示分配采购id
        item.purchaser = purchaserPeople;
        return item;
      });
  });
};
/***获取采购任务结束**/

/***分配任务开始 **/
const atdata = {
  token: token,
  Purchaseordertesk_id: "",
  item: [],
};
// 控制分配列
const allocationState = ref(false);
const allocationMethod = (val) => {
  if (val === "AssignTasks") {
    allocationState.value = true;
  } else {
    //分配保存放这里做
    let items = takeDetailList.value.map((item) => {
      return {
        Purchaseordertesk_detailed_id: item.Purchaseordertesk_detailed_id,
        Purchaser_id: item.purcharse,
        quantity: item.quantity * 1,
        order_info_id: item.order_info_id,
      };
    });
    items = items.filter((item) => {
      return item.Purchaser_id * 1 !== 0 || item.quantity * 1 !== 0;
    });
    if (items.length == 0) {
      ElMessage({
        type: "info",
        message: "No deployment task is added",
      });
      allocationState.value = false;
      return false;
    }
    atdata.item = items;
    atdata.Purchaseordertesk_id = purchaseordertesk_id.value;
    api.purchaseOrderteskReassign(atdata).then((res) => {
      if (res.Status == 0) {
        ElMessage({
          type: "success",
          message: "Successful deployment",
        });
        // 计算调配后的qty
        takeDetailList.value = takeDetailList.value.map((item) => {
          (item.Qtynumber = item.Qtynumber - item.quantity),
            (item.quantity = ""),
            (item.purcharse = "");
          return item;
        });
        allocationState.value = false;
      }
    });
  }
};
// 分配数量判断
const compare = (row) => {
  utils.debounce(1000, () => {
    if (row.Qtynumber * 1 - row.quantity * 1 < 0) {
      ElMessage({
        type: "info",
        message: "Insufficient allocation",
      });
      takeDetailList.value = takeDetailList.value.map((item) => {
        item.quantity = "";
        return item;
      });
    }
  });
};
/***分配任务结束 **/

/***退回采购任务开始 **/
const renturndata = {
  token: token,
  Purchaseordertesk_detailed_id: "",
  callback_number: "",
};
const returnTask = (val) => {
  if (val.row.Qtynumber == 0) {
    ElMessage({
      type: "info",
      message: "This task cannot be returned",
    });
    return false;
  }
  renturndata.Purchaseordertesk_detailed_id =
    val.row.Purchaseordertesk_detailed_id;
  renturndata.callback_number = val.row.Qtynumber;
  api.purchaseOrderteskCallbackOrder(renturndata).then((res) => {
    if (res.Status == 0) {
      takeDetailList.value.splice(val.$index, 1);
      purcharseTakeList.value.forEach((item, index) => {
        if (item.purchaseordertesk_id == val.row.Purchaseordertesk_id) {
          item.items = item.items - 1;
        }
      });
      ElMessage({
        type: "success",
        message: "Successful return",
      });
    }
  });
};
// 公共的删除取消方法
const cancelEvent = (val) => {
  ElMessage({
    type: "info",
    message: val,
  });
};
/***退回采购任务结束 **/

/***删除采购任务开始 **/
const taskdeldata = {
  token: token,
  Purchaseordertesk_id: "",
};
const taskDelete = () => {
  taskdeldata.Purchaseordertesk_id = purchaseordertesk_id.value;
  ElMessageBox.confirm(
    "Are you sure to delete this purchase order?",
    "Warning",
    {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      distinguishCancelAndClose: true,
    }
  )
    .then(() => {
      api.purchaseOrderteskDelete(taskdeldata).then((res) => {
        if (res.Status == 0) {
          ElMessage({
            type: "success",
            message: "Deleted successfully",
          });
          getpurTakeList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete cancel",
      });
    });
};
/***删除采购任务结束 **/

/***创建采购单开始 **/
const newPurchaseOrder = ref();
// 创建采购单渲染列表
const createList = ref([]);
const openNewOrder = () => {
  getleading();
  getPurOrderInfo();
  // getPsupplierList()
  newPurchaseOrder.value.dialogopen();
};
// 获取创建订单信息
const pInfoData = {
  token: token,
  page: 1,
  purchase_tesk_ids: [],
};
const getPurOrderInfo = () => {
  pInfoData.purchase_tesk_ids = selectList.value.map((item) => {
    return {
      purchaseordertesk_id: item.purchaseordertesk_id,
    };
  });
  api.purchaseOrderteskDetail(pInfoData).then((res) => {
    createList.value = res.data.list.data.map((item) => {
      // 是否走库存
      item.NonStock = false;
      // 创建采购单的采购数量
      item.Pquantity =
        item.Qtynumber * 1 - item.use_number * 1 < 0
          ? 0
          : item.Qtynumber * 1 - item.use_number * 1;
      // 创建采购单的采购价
      item.Pmoney = item.Pquantity == 0 ? 0 : "";
      // 利润
      item.Profits = item.Pquantity == 0 ? 0 : "";
      // 走库房利润
      item.stockProfits = (
        ((item.Price * 1 - item.stock_price * 1) / (item.stock_price * 1)) *
        100
      ).toFixed(2);
      item.stockProfits = isNaN(item.stockProfits) ? 0 : item.stockProfits;
      // 总价
      item.Total = item.Pquantity == 0 ? 0 : "";
      // 走库房数
      item.WarehouseNumber =
        item.use_number > item.Qtynumber ? item.Qtynumber : item.use_number;
      return item;
    });
  });
};
// 获取供应商列表
const pSupplierList = ref([]);
const getPsupplierList = (val) => {
  userdata.is_supplier = 1;
  userdata.kw = val;
  api.orderUser(userdata).then((res) => {
    pSupplierList.value = res.data.data;
  });
};
// 数量输入方法，主要计算总价和判断输入的值是否大于任务数
const inputPqty = (val) => {
  utils.debounce(500, () => {
    createList.value = createList.value.map((item) => {
      if (
        !val.value &&
        item.Pquantity > item.Qtynumber - item.WarehouseNumber
      ) {
        ElMessage({
          type: "info",
          message: "Insufficient allocation",
        });
        item.Pquantity = item.Qtynumber * 1 - item.WarehouseNumber * 1;
      } else if (val.value && item.Pquantity > item.Qtynumber) {
        ElMessage({
          type: "info",
          message: "Insufficient allocation",
        });
        item.Pquantity = item.Qtynumber * 1;
      }
      // 总价
      item.Total = item.Pmoney * item.Pquantity;
      return item;
    });
  });
};
// 价格输入框主要实现计算总价和利润
const inPmoney = () => {
  utils.debounce(500, () => {
    createList.value = createList.value.map((item) => {
      // 总价
      item.Total = item.Pmoney * item.Pquantity;
      // 利润
      item.Profits = (
        ((item.Price * 1 - item.Pmoney * 1) / (item.Pmoney * 1)) *
        100
      ).toFixed(2);
      item.Profits = isNaN(item.Profits) ? 0 : item.Profits;
      return item;
    });
  });
};
// 弹框单项是否走库存
const changeNonStock1 = (val) => {
  createList.value.forEach((item) => {
    if (
      item.Purchaseordertesk_detailed_id == val.Purchaseordertesk_detailed_id
    ) {
      // 是否走库存
      item.NonStock = val.NonStock;
      // 创建采购单的采购数量
      item.Pquantity =
        item.Qtynumber * 1 - item.use_number * 1 < 0
          ? 0
          : item.Qtynumber * 1 - item.use_number * 1;
      item.Pquantity = item.NonStock == false ? item.Pquantity : item.Qtynumber;
      // 创建采购单的采购价
      item.Pmoney = item.Pquantity == 0 ? 0 : "";
      item.Pmoney = item.NonStock == false ? item.Pmoney : "";
      // 利润
      item.Profits = item.Pquantity == 0 ? 0 : "";
      item.Profits = item.NonStock == false ? item.Profits : "";
      // 走库房利润
      item.stockProfits =
        item.NonStock == false
          ? (
              ((item.Price * 1 - item.stock_price * 1) /
                (item.stock_price * 1)) *
              100
            ).toFixed(2)
          : 0;
      item.stockProfits = isNaN(item.stockProfits) ? 0 : item.stockProfits;
      // 总价
      item.Total = item.Pquantity == 0 ? 0 : "";
      item.Total = item.NonStock == false ? item.Total : "";
      // 走库房数
      item.WarehouseNumber =
        item.use_number > item.Qtynumber ? item.Qtynumber : item.use_number;
      item.WarehouseNumber = item.NonStock == false ? item.WarehouseNumber : 0;
    }
  });
};
// 改变走库房数
const changKufang = (val) => {
  utils.debounce(500, () => {
    createList.value.forEach((item) => {
      if (
        item.Purchaseordertesk_detailed_id == val.Purchaseordertesk_detailed_id
      ) {
        if (
          val.WarehouseNumber > item.use_number ||
          val.WarehouseNumber > item.Qtynumber
        ) {
          ElMessage({
            type: "info",
            message: "Invalid data",
          });
          if (item.Qtynumber > item.use_number) {
            item.WarehouseNumber = item.use_number;
          } else {
            item.WarehouseNumber = item.Qtynumber;
          }
          return false;
        }
        // 创建采购单的采购数量
        item.Pquantity =
          item.Qtynumber * 1 - item.WarehouseNumber * 1 < 0
            ? 0
            : item.Qtynumber * 1 - item.WarehouseNumber * 1;
        // 创建采购单的采购价
        item.Pmoney = item.Pquantity == 0 ? 0 : "";
        // 利润
        item.Profits = item.Pquantity == 0 ? 0 : "";
        // 走库房利润
        item.stockProfits = (
          ((item.Price * 1 - item.stock_price * 1) / (item.stock_price * 1)) *
          100
        ).toFixed(2);
        item.stockProfits = isNaN(item.stockProfits) ? 0 : item.stockProfits;
        // 总价
        item.Total = item.Pquantity == 0 ? 0 : "";
      }
    });
  });
};
// 创建采购订单点击事件
const cpoData = {
  token: token,
  item: [],
};
/**
 *
 * @param {*是否库存} NonStock
 * @param {*供应商Id} pSupplierID
 *
 */
const CreatePurchaseOrder = (NonStock, pSupplierID) => {
  let items = [];
  items = createList.value.map((item) => {
    if (NonStock) {
      return {
        customer_info_id: pSupplierID,
        Purchaseordertesk_detailed_id: item.Purchaseordertesk_detailed_id,
        products_id: item.products_id,
        Qtynumber: item.Pquantity * 1,
        Purchase_price: item.Pmoney,
        Profit: item.Profits,
        lead: item.lead.replace(/\r/, ""),
        is_stock: 0,
      };
    } else {
      if (
        item.Qtynumber > item.WarehouseNumber &&
        item.WarehouseNumber > 0 &&
        item.NonStock == false
      ) {
        return [
          {
            customer_info_id: 0,
            Purchaseordertesk_detailed_id: item.Purchaseordertesk_detailed_id,
            products_id: item.products_id,
            Qtynumber: item.WarehouseNumber,
            Purchase_price: item.stock_price,
            Profit: item.stockProfits,
            lead: item.lead.replace(/\r/, ""),
            is_stock: 1,
          },
          {
            customer_info_id: pSupplierID,
            Purchaseordertesk_detailed_id: item.Purchaseordertesk_detailed_id,
            products_id: item.products_id,
            Qtynumber: item.Pquantity * 1,
            Purchase_price: item.Pmoney,
            Profit: item.Profits,
            lead: item.lead.replace(/\r/, ""),
            is_stock: 0,
          },
        ];
      } else if (
        (item.Qtynumber < item.WarehouseNumber ||
          item.Qtynumber == item.WarehouseNumber) &&
        item.NonStock == false
      ) {
        return {
          customer_info_id: 0,
          Purchaseordertesk_detailed_id: item.Purchaseordertesk_detailed_id,
          products_id: item.products_id,
          Qtynumber: item.Qtynumber,
          Purchase_price: item.stock_price,
          Profit: item.stockProfits,
          lead: item.lead.replace(/\r/, ""),
          is_stock: 1,
        };
      } else {
        return {
          customer_info_id: pSupplierID,
          Purchaseordertesk_detailed_id: item.Purchaseordertesk_detailed_id,
          products_id: item.products_id,
          Qtynumber: item.Pquantity * 1,
          Purchase_price: item.Pmoney,
          Profit: item.Profits,
          lead: item.lead.replace(/\r/, ""),
          is_stock: 0,
        };
      }
    }
  });
  let itemList = [];
  items.forEach((item) => {
    if (Array.isArray(item)) {
      item.forEach((item1) => {
        itemList.push(item1);
      });
    } else {
      itemList.push(item);
    }
  });
  cpoData.item = itemList;
  if (!utils.isObjectNull(cpoData)) {
    ElMessage({
      type: "info",
      message: `Please enter the complete information`,
    });
    return false;
  }
  api.purchaseOrderAdd(cpoData).then((res) => {
    if (res.Status == 0) {
      newPurchaseOrder.value.open = false;
      ElMessage({
        type: "success",
        message: "Add successfully",
      });
      newPurchaseOrder.value.pSupplierID = "";
      createList.value = [];
      purcharseTakeList.value.forEach((item) => {
        if (item.purchaseordertesk_id == purchaseordertesk_id.value) {
          item.State = 2;
          item.state_text = "采购中";
        }
      });
      getPurchaseOrderList();
    }
  });
};

//是否走库存选择方法
const changeNonStock = (NonStock) => {
  createList.value = createList.value.map((item) => {
    if (NonStock) {
      // 这里点击不走库存后，直接将输入框赋值为任务数量以及清空走库存情况下计算的数据
      item.Pquantity = item.Qtynumber;
      item.Pmoney = "";
      item.Profits = "";
      item.Total = "";
    } else {
      // 这里判断输入的数量如果任务数量小于库房数，则输入数量为0，否则就按计算值赋值给输入框
      item.Pquantity =
        item.Qtynumber * 1 - item.use_number * 1 < 0
          ? 0
          : item.Qtynumber * 1 - item.use_number * 1;
      // 判断待采购数量是否为0为0则代表库存足够，不需要采购将利润与采购、总数均设置为0,不为0则清空
      item.Pmoney = item.Pquantity == 0 ? 0 : "";
      item.Total = item.Pquantity == 0 ? 0 : "";
      item.Profits = item.Pquantity == 0 ? 0 : "";
    }
    return item;
  });
};
// 删除按钮方法
const delecteTacke = (val) => {
  createList.value.splice(val.$index, 1);
};
/***创建采购单结束 **/

/***获取采购单开始**/
const poLeading = ref(true);
const purorderdata = {
  token: token,
  page: "",
};
// 采购单ID
const purchaseOrderDetailList = ref([]);
const getPurchaseOrderList = () => {
  purorderdata.page = 1;
  api.purchaseOrderList(purorderdata).then((res) => {
    poLeading.value = false;
    purchaseOrderDetailList.value =
      res.data.data &&
      res.data.data.map((item) => {
        item.firstname = item.firstname.slice(0, 5);
        return item;
      });
    getPurchaseOrderListDetail();
  });
};
const purorderlength = ref();
const getPurchaseOrderList1 = () => {
  if (purchaseOrderDetailList.value.length == 0 || purorderlength.value == 0)
    return false;
  purorderdata.page++;
  api.purchaseOrderList(purorderdata).then((res) => {
    purorderlength.value = res.data.data && res.data.data.length;
    purchaseOrderDetailList.value = [
      ...purchaseOrderDetailList.value,
      ...res.data.data.map((item) => {
        item.firstname = item.firstname.slice(0, 5);
        return item;
      }),
    ];
  });
};
// 获取采购单详情
const porderData = {
  token: token,
  Purchaseorder_id: "",
  page: 1,
};
// 采购单状态
const pState = ref();
const poDetailLeading = ref(false);
const purchaseorder_id = ref("");
const purOrderDetailList = ref([]);
//默认
const getPurchaseOrderListDetail = () => {
  poDetailLeading.value = true;
  pState.value =
    purchaseOrderDetailList.value && purchaseOrderDetailList.value[0].State;
  purchaseorder_id.value =
    purchaseOrderDetailList.value &&
    purchaseOrderDetailList.value[0].purchaseorder_id * 1;
  porderData.Purchaseorder_id =
    purchaseOrderDetailList.value &&
    purchaseOrderDetailList.value[0].purchaseorder_id;
  purOrderDetail();
};
// 点击
const getPurOrderID = (row) => {
  poDetailLeading.value = true;
  pState.value = row.State;
  purchaseorder_id.value = row.purchaseorder_id * 1;
  porderData.Purchaseorder_id = row.purchaseorder_id;
  purOrderDetail();
};
const purOrderDetail = () => {
  api.purchaseOrderDetailed(porderData).then((res) => {
    poDetailLeading.value = false;
    purOrderDetailList.value =
      res.data.data &&
      res.data.data.map((item) => {
        item.State = utils.fPurState(item.State);
        return item;
      });
  });
};
/***获取采购单结束**/

/*** 导出采购单开始**/
const shortcuts = [
  {
    text: "Past 07 Days",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "Past 30 Days",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "Past 90 Days",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

const exportPurOrder = ref();
const epdata = {
  token: token,
  purchaseorder_id: "",
  start_time: "",
  end_time: "",
};
const exportPurList = ref([]);
const sumProfit = ref(0);
const getdate = (val) => {
  epdata.purchaseorder_id = purchaseorder_id.value;
  if (!!val) {
    epdata.start_time = utils.ftime(
      val.map((item) => new Date(item).getTime())[0]
    );
    epdata.end_time = utils.ftime(
      val.map((item) => new Date(item).getTime())[1]
    );
    api.purchaseOrderExportPurchase(epdata).then((res) => {
      exportPurList.value = res.data.map((item, index) => {
        item.Number = index + 1;
        item.ProfitMoney = item.Total * 1 * (item.Profit * 1);
        return item;
      });
      sumProfit.value = exportPurList.value.reduce((sum, item) => {
        return sum + item.ProfitMoney;
      }, 0);
      sumProfit.value = sumProfit.value.toFixed(2);
    });
  } else {
    exportPurList.value = [];
    sumProfit.value = 0;
    sumProfit.value = 0;
  }
};
const ExportPorder = () => {
  exportPurOrder.value.dialogopen();
};
// 关闭弹窗
const closeEpurWindow = () => {
  exportPurList.value = [];
  sumProfit.value = "";
  exportPurOrder.value.date = [];
  exportPurOrder.value.open = false;
};
/*** 导出采购单结束**/

/*** 采购单更改采购价开始**/
const choosePrice = () => {
  utils.debounce(500, () => {
    purOrderDetailList.value = purOrderDetailList.value.map((item) => {
      // 更改价格时改变总价和利润
      item.Total = item.cost * item.dty;
      item.Profit = (
        ((item.price * 1 - item.cost * 1) / (item.cost * 1)) *
        100
      ).toFixed(2);
      return item;
    });
  });
};
const changePriceData = {
  token: token,
  item: [],
};

const priceState = ref(false);
const ChangeThePrice = (name) => {
  if (pState.value !== 1) {
    ElMessage({
      type: "info",
      message: "The price cannot be changed after payment",
    });
    return false;
  }
  let items = purOrderDetailList.value.map((item) => {
    return {
      purchaseorder_detailed_id: item.Purchaseorder_detailed_id,
      Purchase_price: item.cost,
      Total: item.Total,
      Profit: item.Profit,
    };
  });
  changePriceData.item = items;
  if (name == "ChangePrice") {
    priceState.value = true;
  } else {
    // 保存价格
    api.purchaseOrderEditPrice(changePriceData).then((res) => {
      if (res.Status == 0) {
        ElMessage({
          type: "success",
          message: "Change successfully",
        });
      }
      priceState.value = false;
    });
  }
};
/*** 采购单更改采购价结束**/

/*** 删除采购单开始**/
const delPurOrderData = {
  token: token,
  purchaseorder_id: "",
};
const deletePurchaseOrder = () => {
  delPurOrderData.purchaseorder_id = purchaseorder_id.value;
  ElMessageBox.confirm(
    "Are you sure to delete this purchase order?",
    "Warning",
    {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      distinguishCancelAndClose: true,
    }
  )
    .then(() => {
      api.purchaseOrderDelete(delPurOrderData).then((res) => {
        if (res.Status == 0) {
          ElMessage({
            type: "success",
            message: "Deleted successfully",
          });
          getPurchaseOrderList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete cancel",
      });
    });
};
/*** 删除采购单结束**/

/*** 删除采购订单详情开始**/
const delPurDetailData = {
  token: token,
  purchaseorder_detailed_id: "",
};
const delPurchaseDetails = (info) => {
  delPurDetailData.purchaseorder_detailed_id =
    info.row.Purchaseorder_detailed_id;
  api.purchaseOrderDeleteDetailed(delPurDetailData).then((res) => {
    if (res.Status == 0) {
      ElMessage({
        type: "success",
        message: "Deleted successfully",
      });
      purOrderDetailList.value.splice(info.$index, 1);
    }
  });
};
/*** 删除采购订单详情结束**/

/********************************采购单逻辑结束******************************************** */
watch([state], () => {
  if (radio1.value === 2) return false;
  api.ordersProductRecord(curveDiagramdata).then((res) => {
    purchaseList.value = res.data.purchase;
    salesList.value = res.data.sale;
    purchaseChart1.value &&
      purchaseChart1.value.init(purchaseList.value, salesList.value);
  });
});
//采购销售公共搜索
const searchOrderList = (val) => {
  if (radio1.value === "1") {
    data.PI_name = val;
    if (!val) {
      sorderRequest();
    } else {
      utils.debounce(500, () => {
        sorderRequest();
      });
    }
  } else {
    takedata.PI_name = val;
    if (!val) {
      porderRequest();
    } else {
      utils.debounce(500, () => {
        porderRequest();
      });
    }
  }
};

onMounted(() => {
  confirmPermission();
  radio1.value == "1" ? getOrderList() : "";
  radio1.value == "2" ? getpurTakeList() : "";
  radio1.value == "2" ? getPurchaseOrderList() : "";
});
</script>
<style lang="less">
@import url(./order.less);
</style>
